package com.example.kotlin01.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.kotlin01.database.AppDatabase
import com.example.kotlin01.model.User
import com.example.kotlin01.repository.UserRepository
import kotlinx.coroutines.launch

//加val就是作为成员变量（val repository: UserRepository）
class UserViewModel constructor(application: Application) : AndroidViewModel(application) {
    val repository: UserRepository

    init {
        repository = UserRepository(
            AppDatabase.AppDataBaseSingleClass.getInstance(application)!!
                .getUserDao()
        )
    }

    val userLiveData: MutableLiveData<List<User>> = MutableLiveData()


    fun queryUser() {
        //// suspend 和 resume 使得这个数据库请求是主线程安全的，所以 ViewModel 不需要关心线程安全问题
        viewModelScope.launch {
            userLiveData.value = repository.queryUser()
        }
    }

    fun addUser(user: User) {
        //// suspend 和 resume 使得这个数据库请求是主线程安全的，所以 ViewModel 不需要关心线程安全问题
        viewModelScope.launch {
            val result = repository.addUser(user)
            Log.e("UserViewModel", "addUser: " + result)
        }
    }

    fun deleteUser(user: User) {
        //// suspend 和 resume 使得这个数据库请求是主线程安全的，所以 ViewModel 不需要关心线程安全问题
        viewModelScope.launch {
            val result = repository.deleteUser(user)
            Log.e("UserViewModel", "addUser: " + result)
        }
    }
}